package com.jh3502.helper.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.jh3502.helper.function.person.personlist.PersonListBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ExcelUtil {
    private static ExcelUtil excelUtil;
    //内存地址
    @NonNull
    public String root = Environment.getExternalStorageDirectory().getPath();

    public static synchronized ExcelUtil getInstance() {
        if (excelUtil == null) {
            excelUtil = new ExcelUtil();
        }
        return excelUtil;
    }

    public void writeExcel(Context context, @NonNull List<PersonListBean> exportOrder,
                           String fileName) throws Exception {
//		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)&&getAvailableStorage()>1000000) {
//			Toast.makeText(context, "SD卡不可用", Toast.LENGTH_LONG).show();
//			return;
//		}

        String[] title = {"订单", "店名", "电话", "地址"};
        File file;
//		File dir = new File(context.getExternalFilesDir(null).getPath());
        File dir = new File(Environment.getExternalStorageDirectory(), "Jh3502");
        file = new File(dir, fileName + ".xls");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 创建Excel工作表
        WritableWorkbook wwb;
        OutputStream os = new FileOutputStream(file);
        wwb = Workbook.createWorkbook(os);
        // 添加第一个工作表并设置第一个Sheet的名字
        WritableSheet sheet = wwb.createSheet("订单", 0);
        Label label;
        for (int i = 0; i < title.length; i++) {
            // Label(x,y,z) 代表单元格的第x+1列，第y+1行, 内容z
            // 在Label对象的子对象中指明单元格的位置和内容
            label = new Label(i, 0, title[i], getHeader());
            // 将定义好的单元格添加到工作表中
            sheet.addCell(label);
        }

        for (int i = 0; i < exportOrder.size(); i++) {
            PersonListBean order = exportOrder.get(i);

            Label orderNum = new Label(0, i + 1, order.getName());
            Label restaurant = new Label(1, i + 1, order.getAge());

            sheet.addCell(orderNum);
            sheet.addCell(restaurant);
            Toast.makeText(context, "写入成功", Toast.LENGTH_LONG).show();

        }
        // 写入数据
        wwb.write();
        // 关闭文件
        wwb.close();
    }

    @NonNull
    public WritableCellFormat getHeader() {
        WritableFont font = new WritableFont(WritableFont.TIMES, 10,
                WritableFont.BOLD);// 定义字体
        try {
            font.setColour(Colour.BLUE);// 蓝色字体
        } catch (WriteException e1) {
            e1.printStackTrace();
        }
        WritableCellFormat format = new WritableCellFormat(font);
        try {
            format.setAlignment(jxl.format.Alignment.CENTRE);// 左右居中
            format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);// 上下居中
            // format.setBorder(Border.ALL, BorderLineStyle.THIN,
            // Colour.BLACK);// 黑色边框
            // format.setBackground(Colour.YELLOW);// 黄色背景
        } catch (WriteException e) {
            e.printStackTrace();
        }
        return format;
    }

    /**
     * 获取SD可用容量
     */
    private long getAvailableStorage() {

        StatFs statFs = new StatFs(root);
        long blockSize = statFs.getBlockSize();
        long availableBlocks = statFs.getAvailableBlocks();
        long availableSize = blockSize * availableBlocks;
        // Formatter.formatFileSize(context, availableSize);
        return availableSize;
    }

    //将excel文件导入到内存中

    @Nullable
    public Map<String, Object> importExcelData(@NonNull String path) {
//        ArrayList<PersonListBean> datas = new ArrayList<>();
        Workbook workbook = null;
        try {
            workbook = Workbook.getWorkbook(new File(path));
            Sheet sheet = workbook.getSheet(0);
            int rows = sheet.getRows();
            int columns = sheet.getColumns();
            Map<String, Object> orgMap = new HashMap<>(2);
//            Map<String,Object> depMap = new HashMap<>(2);

            //遍历excel文件的每行每列
            for (int i = 0; i < rows; i++) {
                Log.e("3502", "rows:" + i);
                //遍历行
                List<String> li = new ArrayList<>();
                for (int j = 0; j < columns; j++) {
                    Cell cell = sheet.getCell(j, i);
                    String result = cell.getContents();
                    if (i != 0) {
                        li.add(result);
                    }
                }
                if (li.size() > 0) {
                    PersonListBean personListBean = new PersonListBean();
                    personListBean.setPno(UUID.randomUUID().toString());
                    personListBean.setName(li.get(3));
                    String sex = li.get(4);
                    if ("男".equals(sex)) {
                        personListBean.setSex(0);
                    } else if ("女".equals(sex)) {
                        personListBean.setSex(1);
                    } else {
                        personListBean.setSex(2);
                    }

                    personListBean.setOrg(li.get(1));
                    personListBean.setDep(li.get(2));
                    personListBean.setNamePinyin(PinyinUtil.getInstance().getPinyin(li.get(3).substring(0, 2)));

                    if (!orgMap.containsKey(li.get(1))) {
                        Map<String, Object> depMap = new HashMap<>(2);
                        List<PersonListBean> peresonList = new ArrayList<>(2);
                        peresonList.add(personListBean);
                        depMap.put(li.get(2), peresonList);
                        orgMap.put(li.get(1), depMap);
                    } else {
                        Map<String, Object> depMap = (Map<String, Object>) orgMap.get(li.get(1));
                        if (!depMap.containsKey(li.get(2))) {
                            List<PersonListBean> peresonList = new ArrayList<>(2);
                            peresonList.add(personListBean);
                            depMap.put(li.get(2), peresonList);
                        } else {
                            List<PersonListBean> peresonList = (List<PersonListBean>) depMap.get(li.get(2));
                            peresonList.add(personListBean);
                        }

                    }
                    Log.e("3502", orgMap.toString());


                }
                li = null;
            }
            return orgMap;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        return null;
    }

}
